package com.qixin.modules.eaApplication.controller;


import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.qixin.modules.ea.service.IEaPhoneRecordService;
import com.qixin.modules.eaApplication.vo.EaEntertainApplyPrintVo;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.util.ConvertUpMoneyUtil;
import org.jeecg.common.util.FillRuleUtil;
import org.jeecg.modules.activity.service.ActivityCommonService;
import org.jeecg.modules.nc.entity.NcPersonnel;
import org.jeecg.modules.nc.service.INcPersonnelService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import com.qixin.modules.eaApplication.entity.EaHostObject;
import com.qixin.modules.ea.entity.EaPhoneRecord;
import com.qixin.modules.ea.entity.EaEntertainReceptionActivity;
import com.qixin.modules.eaApplication.entity.EaEntertainApply;
import com.qixin.modules.eaApplication.vo.EaEntertainApplyPage;
import com.qixin.modules.eaApplication.service.IEaEntertainApplyService;
import com.qixin.modules.eaApplication.service.IEaHostObjectService;
import com.qixin.modules.ea.service.IEaEntertainReceptionActivityService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: ea_entertain_apply
 * @Author: qixin-boot
 * @Date:   2022-01-21
 * @Version: V1.0
 */
@Api(tags="招待费申请单")
@RestController
@RequestMapping("/eaApplication/eaEntertainApply")
@Slf4j
public class EaEntertainApplyController {
	@Autowired
	private IEaEntertainApplyService eaEntertainApplyService;
	@Autowired
	private IEaHostObjectService eaHostObjectService;
	@Autowired
	private IEaPhoneRecordService eaPhoneRecordService;
	@Autowired
	private IEaEntertainReceptionActivityService eaEntertainReceptionActivityService;
	@Autowired
	private INcPersonnelService ncPersonnelService;
	// 工作流公共执行类
	@Autowired
	private ActivityCommonService activityCommonService;
	
	/**
	 * 分页列表查询
	 *
	 * @param eaEntertainApply
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@ApiOperation(value="招待费申请单-分页列表查询", notes="招待费申请单-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(EaEntertainApply eaEntertainApply,
								   @RequestParam(name="billDateBegin", required = false) String billDateBegin,
								   @RequestParam(name="billDateEnd", required = false) String billDateEnd,
								   @RequestParam(name="userid", required = false) String userid,
								   @RequestParam(name="billCode", required = false) String billCode,
								   @RequestParam(name="isUse", required = false) String isUse,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<EaEntertainApply> queryWrapper = QueryGenerator.initQueryWrapper(eaEntertainApply, req.getParameterMap());
		//add-begin-by wujinbiao for 添加查询条件
		if (StringUtils.isNotBlank(billDateBegin)){
			queryWrapper.ge("bill_date", billDateBegin);
		}
		if (StringUtils.isNotBlank(billDateEnd)){
			queryWrapper.le("bill_date", billDateEnd);
		}
		if (StringUtils.isNotBlank(userid)){
			queryWrapper.eq("person_id", userid);
		}
		if(StringUtils.isNotBlank(billCode)){
			// 单据编号模糊查询
			queryWrapper.like("bill_no",billCode);
		}
		queryWrapper.orderByDesc("create_time");
		LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		if(isUse == null){
			queryWrapper.and(
					wrapper -> wrapper.eq("create_by",loginUser.getId()).or().eq("person_id",loginUser.getPkPsndoc())
			);
		}
		if(StringUtils.isNotBlank(isUse) && "1".equals(isUse)){
			// 过滤已被报销的申请单
			queryWrapper.and(
					wrapper -> wrapper.isNull("ea_entertain_id").or().eq("ea_entertain_id","")
			);
		}
		//add-begin-by wujinbiao for 添加查询条件

		Page<EaEntertainApply> page = new Page<EaEntertainApply>(pageNo, pageSize);
		IPage<EaEntertainApply> pageList = eaEntertainApplyService.page(page, queryWrapper);
		//add-begin-by wujinbiao for 详情返回申请人名称
		List<EaEntertainApply> records = pageList.getRecords();
		for (EaEntertainApply eaEntertainApply1: records) {
			NcPersonnel ncPersonnel = ncPersonnelService.queryById(eaEntertainApply1.getPersonId());
			if(ncPersonnel != null){
				eaEntertainApply1.setPersonIdName(ncPersonnel.getName());
			}
		}
		//add-end-by wujinbiao for 详情返回申请人名称
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param eaEntertainApplyPage
	 * @return
	 */
	@AutoLog(value = "招待费申请单-添加")
	@ApiOperation(value="招待费申请单-添加", notes="招待费申请单-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody EaEntertainApplyPage eaEntertainApplyPage) {
		EaEntertainApply eaEntertainApply = new EaEntertainApply();
		BeanUtils.copyProperties(eaEntertainApplyPage, eaEntertainApply);

		// update-begin-Autor: wjb date: 2022-02-09 10:47 for: 生成单据编号
		JSONObject jsonObj = new JSONObject();
		jsonObj.put("prefix","ZDSQ"); // 编码前缀
		Object result = FillRuleUtil.executeRule("common_code", jsonObj);
		eaEntertainApply.setBillNo(result.toString());
		// update-end-Autor: wjb date: 2022-02-09 10:47 for: 生成单据编号
		eaEntertainApply.setState(0);
		eaEntertainApplyService.saveMain(eaEntertainApply, eaEntertainApplyPage.getEaHostObjectList(),eaEntertainApplyPage.getEaEntertainReceptionActivities(),eaEntertainApplyPage.getEaPhoneRecord());
		//add-begin-by 2022-02-07 wjb for 返回主表、子表数据给前端
		EaEntertainApplyPage resultPage = new EaEntertainApplyPage();
		BeanUtils.copyProperties(eaEntertainApply,resultPage);
		resultPage.setEaHostObjectList(eaEntertainApplyPage.getEaHostObjectList());
		resultPage.setEaEntertainReceptionActivities(eaEntertainApplyPage.getEaEntertainReceptionActivities());
		resultPage.setEaPhoneRecord(eaEntertainApplyPage.getEaPhoneRecord());
		//add-end-by 2022-02-07 wjb for 返回主表、子表数据给前端
		return Result.OK(resultPage);
	}
	
	/**
	 *  编辑
	 *
	 * @param eaEntertainApplyPage
	 * @return
	 */
	@AutoLog(value = "招待费申请单-编辑")
	@ApiOperation(value="招待费申请单-编辑", notes="招待费申请单-编辑")
	@PostMapping(value = "/edit")
	public Result<?> edit(@RequestBody EaEntertainApplyPage eaEntertainApplyPage) {
		EaEntertainApply eaEntertainApply = new EaEntertainApply();
		BeanUtils.copyProperties(eaEntertainApplyPage, eaEntertainApply);
		EaEntertainApply eaEntertainApplyEntity = eaEntertainApplyService.getById(eaEntertainApply.getId());
		if(eaEntertainApplyEntity==null) {
			return Result.error("未找到对应数据");
		}
		eaEntertainApply.setSaveType("add");    //保存
		eaEntertainApplyService.updateMain(eaEntertainApply, eaEntertainApplyPage.getEaHostObjectList(),eaEntertainApplyPage.getEaEntertainReceptionActivities(),eaEntertainApplyPage.getEaPhoneRecord());
		//add-begin-by 2022-02-07 wjb for 返回主表、子表数据给前端
		EaEntertainApplyPage eaEntertainApplyPage1 = new EaEntertainApplyPage();
		BeanUtils.copyProperties(eaEntertainApply,eaEntertainApplyPage1);
		eaEntertainApplyPage1.setEaHostObjectList(eaEntertainApplyPage.getEaHostObjectList());
		eaEntertainApplyPage1.setEaEntertainReceptionActivities(eaEntertainApplyPage.getEaEntertainReceptionActivities());
		eaEntertainApplyPage1.setEaPhoneRecord(eaEntertainApplyPage.getEaPhoneRecord());
		//add-end-by 2022-02-07 wjb for 返回主表、子表数据给前端
		return Result.OK(eaEntertainApplyPage1);
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "招待费申请单-通过id删除")
	@ApiOperation(value="招待费申请单-通过id删除", notes="招待费申请单-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		QueryWrapper<EaEntertainApply> params = new QueryWrapper<>();
		params.eq("id",id);
		EaEntertainApply eaEntertainApply = eaEntertainApplyService.getOne(params);
		if (eaEntertainApply != null && eaEntertainApply.getState()>0){
			return Result.error("该单据已发起流程,不可删除!");
		}
		eaEntertainApplyService.delMain(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "招待费申请单-批量删除")
	@ApiOperation(value="招待费申请单-批量删除", notes="招待费申请单-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.eaEntertainApplyService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功！");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@ApiOperation(value="招待费申请单-通过id查询", notes="招待费申请单-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		EaEntertainApplyPage eaEntertainApplyPage = new EaEntertainApplyPage();
		EaEntertainApply eaEntertainApply = eaEntertainApplyService.getById(id);
		if(eaEntertainApply==null) {
			return Result.error("未找到对应数据");
		}
		//add-begin-by wjb for 详情返回申请人名称、子表数据
		if(StringUtils.isNotBlank(eaEntertainApply.getPersonId())){
			NcPersonnel ncPersonnel = ncPersonnelService.queryById(eaEntertainApply.getPersonId());
			eaEntertainApply.setPersonIdName(ncPersonnel.getName());
		}
		BeanUtils.copyProperties(eaEntertainApply,eaEntertainApplyPage);
		//招待对象子表
		List<EaHostObject> eaHostObjects = eaHostObjectService.selectByMainId(eaEntertainApply.getId());
		List<EaEntertainReceptionActivity> eaEntertainReceptionActivities = eaEntertainReceptionActivityService.selectByMainId(eaEntertainApply.getId());
		List<EaPhoneRecord> eaPhoneRecords = eaPhoneRecordService.selectByMainId(eaEntertainApply.getId());
		eaEntertainApplyPage.setEaHostObjectList(eaHostObjects);
		eaEntertainApplyPage.setEaEntertainReceptionActivities(eaEntertainReceptionActivities);
		eaEntertainApplyPage.setEaPhoneRecord(eaPhoneRecords.get(0));
		//add-end-by wjb for 详情返回申请人名称、子表数据
		return Result.OK(eaEntertainApplyPage);
	}


	 /**
	 * @Description 招待费申请单打印模板-通过id查询
	 * @author  wujinbiao
	 * @date 2022/2/8
	 * @param id
	 * @return org.jeecg.common.api.vo.Result<?>
	 */
	 @ApiOperation(value="招待费申请单打印模板-通过id查询", notes="招待费申请单打印模板-通过id查询")
	 @GetMapping(value = "/selectById")
	 public Result<?> selectById(@RequestParam(name="id",required=true) String id) {
		 EaEntertainApply eaEntertainApply = eaEntertainApplyService.getById(id);
		 if(eaEntertainApply==null) {
			 return Result.error("未找到对应数据");
		 }
		 EaEntertainApplyPrintVo eaEntertainApplyPrintVo = new EaEntertainApplyPrintVo();
		 BeanUtils.copyProperties(eaEntertainApply,eaEntertainApplyPrintVo);

		 eaEntertainApplyPrintVo.setTzrq(eaEntertainApply.getBillDate());

		 // 获取接待对象和人数
		 List<EaHostObject> eaHostObjectList = eaHostObjectService.selectByMainId(id);
		 String hostObjectName = "";
		 if(eaHostObjectList != null && eaHostObjectList.size() > 0){
			 for (int i = 0; i < eaHostObjectList.size(); i++) {
				 Map<String,Object> eaHostObjectMap2 = JSON.parseObject(JSON.toJSONString(eaHostObjectList.get(i), SerializerFeature.WriteMapNullValue), Map.class);
				 // 获取接待对象并拼接成字符串
				 hostObjectName += "" + eaHostObjectMap2.get("hostObject") + ",";
			 }
		 }
		 // 预算费用转为大写金额
		 String amount_cn = eaEntertainApply.getAmount()!= null ? eaEntertainApply.getAmount().toString() : "0";
		 amount_cn = ConvertUpMoneyUtil.toChinese(amount_cn);
		 eaEntertainApplyPrintVo.setAmount_cn(amount_cn);

		 eaEntertainApplyPrintVo.setHostObjectName(hostObjectName.substring(0,hostObjectName.length()-1)+" 共"+eaHostObjectList.size()+"人");
		 List<EaEntertainReceptionActivity> eaEntertainReceptionActivityList = eaEntertainReceptionActivityService.selectByMainId(id);
		 eaEntertainApplyPrintVo.setEaEntertainReceptionActivities(eaEntertainReceptionActivityList);

		 // update-begin-Autor: wjb date: 2022-02-10 15:07 for: 添加流程审批记录
		 if (StringUtils.isNotBlank(eaEntertainApply.getProcInstId())){
			 List<Map<String, Object>> nodeList = activityCommonService.getNodeList(eaEntertainApply.getProcInstId());
			 eaEntertainApplyPrintVo.setSpjl(nodeList);
		 }
		 // update-end-Autor: wjb date: 2022-02-10 15:07 for: 添加流程审批记录

		 return Result.OK(eaEntertainApplyPrintVo);
	 }


	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@ApiOperation(value="招待对象-主表ID查询", notes="招待对象-通主表ID查询")
	@GetMapping(value = "/queryEaHostObjectByMainId")
	public Result<?> queryEaHostObjectListByMainId(@RequestParam(name="id",required=true) String id) {
		List<EaHostObject> eaHostObjectList = eaHostObjectService.selectByMainId(id);
		return Result.OK(eaHostObjectList);
	}
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@ApiOperation(value="电话记录单-主表ID查询", notes="电话记录单-通主表ID查询")
	@GetMapping(value = "/queryEaPhoneRecordByMainId")
	public Result<?> queryEaPhoneRecordListByMainId(@RequestParam(name="id",required=true) String id) {
		List<EaPhoneRecord> eaPhoneRecordList = eaPhoneRecordService.selectByMainId(id);
		return Result.OK(eaPhoneRecordList);
	}
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@ApiOperation(value="活动内容-主表ID查询", notes="活动内容-通主表ID查询")
	@GetMapping(value = "/queryEaEntertainReceptionActivityByMainId")
	public Result<?> queryEaEntertainReceptionActivityListByMainId(@RequestParam(name="id",required=true) String id) {
		List<EaEntertainReceptionActivity> eaEntertainReceptionActivityList = eaEntertainReceptionActivityService.selectByMainId(id);
		return Result.OK(eaEntertainReceptionActivityList);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param eaEntertainApply
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, EaEntertainApply eaEntertainApply) {
      // Step.1 组装查询条件查询数据
      QueryWrapper<EaEntertainApply> queryWrapper = QueryGenerator.initQueryWrapper(eaEntertainApply, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

      //Step.2 获取导出数据
      List<EaEntertainApply> queryList = eaEntertainApplyService.list(queryWrapper);
      // 过滤选中数据
      String selections = request.getParameter("selections");
      List<EaEntertainApply> eaEntertainApplyList = new ArrayList<EaEntertainApply>();
      if(oConvertUtils.isEmpty(selections)) {
          eaEntertainApplyList = queryList;
      }else {
          List<String> selectionList = Arrays.asList(selections.split(","));
          eaEntertainApplyList = queryList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
      }

      // Step.3 组装pageList
      List<EaEntertainApplyPage> pageList = new ArrayList<EaEntertainApplyPage>();
      for (EaEntertainApply main : eaEntertainApplyList) {
          EaEntertainApplyPage vo = new EaEntertainApplyPage();
          BeanUtils.copyProperties(main, vo);
          List<EaHostObject> eaHostObjectList = eaHostObjectService.selectByMainId(main.getId());
          vo.setEaHostObjectList(eaHostObjectList);
          List<EaPhoneRecord> eaPhoneRecordList = eaPhoneRecordService.selectByMainId(main.getId());
          vo.setEaPhoneRecord(eaPhoneRecordList.get(0));
          List<EaEntertainReceptionActivity> eaEntertainReceptionActivityList = eaEntertainReceptionActivityService.selectByMainId(main.getId());
          vo.setEaEntertainReceptionActivities(eaEntertainReceptionActivityList);
          pageList.add(vo);
      }

      // Step.4 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "ea_entertain_apply列表");
      mv.addObject(NormalExcelConstants.CLASS, EaEntertainApplyPage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("ea_entertain_apply数据", "导出人:"+sysUser.getRealname(), "ea_entertain_apply"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          MultipartFile file = entity.getValue();// 获取上传文件对象
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<EaEntertainApplyPage> list = ExcelImportUtil.importExcel(file.getInputStream(), EaEntertainApplyPage.class, params);
              for (EaEntertainApplyPage page : list) {
                  EaEntertainApply po = new EaEntertainApply();
                  BeanUtils.copyProperties(page, po);
                  eaEntertainApplyService.saveMain(po, page.getEaHostObjectList(),page.getEaEntertainReceptionActivities(),page.getEaPhoneRecord());
              }
              return Result.OK("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.OK("文件导入失败！");
    }

}
